<template>
    <div class="image_paint" ref="paint" :width="width" :height="height">
        <canvas class="paint" ref="drawingboard" 
        :width="width"
        :height="height"
        @mousemove="onPaint"></canvas>
        <div class="paint_toolbar clean">
            <div class="left">
                <span>画笔</span>
                <el-select v-model="lineWidth" placeholder="请选择">
                    <el-option
                      v-for="item in lineWidths"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                      <div class="lineWidth" :style="{ height: item.value+'px' }"></div>
                    </el-option>
                </el-select>
                <el-button plain circle size="small" icon="iconfont icon-xuanzhuan3" @click="onClockwise"></el-button>
                <el-button plain circle size="small" icon="iconfont icon-xuanzhuan" @click="onAnticlockwise"></el-button>
                <!-- <el-button plain circle size="small" icon="el-icon-plus" @click="onZoomIn"></el-button>
                <el-button plain circle size="small" icon="el-icon-minus" @click="onZoomOut"></el-button> -->
            </div>
            <div class="right">
                <el-button type="primary" size="small" @click="onSave">保存</el-button>
                <el-button type="warning" size="small" @click="onReset">重置</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Watch } from 'vue-property-decorator';

    @Component({
        props: {
            image: {
                type: String,
                required: true
            },
            width: {
                type: Number,
                default: 1000
            },
            height: {
                type: Number,
                default: 700
            }
        },
        watch: {
            lineWidth(newVal, oldVal) {
                this.switchCxt()
            },
            image(newVal, oldVal) {
                this.loadImage()
            }
        }
    })
    export default class ImagePaint extends Vue {
        // image = 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/be467f06-2afd-4e2d-a3cb-669b67d7dca6.jpg'
        context:CanvasRenderingContext2D = null
        originImageData:HTMLImageElement = null
        rotateAngle = 0 // [0, 90, 180, 270]
        lineWidths = [
            { value: 3, label: '极细' },
            { value: 5, label: '细' }, 
            { value: 10, label: '普通' }, 
            { value: 15, label: '粗' }, 
            { value: 20, label: '极粗' }
        ]
        lineWidth = 10
        isPainting = false
        colors = [ '#505050', '#6E6E6E', '#8C8C8C', '#AAAAAA', '#C8C8C8', '#E6E6E6' ]
        colorIndex = 0

        /**
         * 涂抹
         * @MouseMove Event e
         */
        onPaint(e:Event) {
            if (e.buttons == 1) {
                let {x, y}  = this.windowToCanvas(this.$refs.drawingboard, e.clientX, e.clientY)
                if (this.colorIndex == this.colors.length) {
                    this.colorIndex = 0;
                }
                this.context.strokeStyle = this.colors[this.colorIndex++];
                this.context.beginPath();
                this.context.moveTo(x, y);
                this.context.lineTo(x, y);
                this.context.stroke();
                this.context.closePath();
            }
        }

        /**
         * 顺时针旋转
         */
        onClockwise() {
            this.rotateAngle == 3 ? this.rotateAngle = 0 : this.rotateAngle+=1;
            this.redraw()
        }

        /**
         * 逆时针旋转
         */
        onAnticlockwise() {
            this.rotateAngle == 0 ? this.rotateAngle = 3 : this.rotateAngle-=1;
            this.redraw()
        }

        /**
         * 保存
         */
        onSave() {
            let self = this;
            this.$refs.drawingboard.toBlob(function(blob){
                let imageUrl = self.removeUrlParam(self.image);
                self.$emit('uploadToOSS', { blob, imageUrl })
            }, 'image/png');
        }

        /**
         * 重置
         */
        onReset() {
            this.redraw()
        }

        /**
         * 放大
         */
        onZoomIn() {
            this.cleanBoard();
            this.context.scale(.5, .5);
            this.redraw();
        }

        /**
         * 缩小
         */
        onZoomOut() {
            this.cleanBoard();
            this.context.scale(.5, .5);
            this.redraw();
        }

        /**
         * 清空画板
         */
        cleanBoard() {
            this.context.clearRect(0, 0, this.width, this.height);
        }

        /**
         * 切换上下文
         */
        switchCxt() {
            this.context.lineWidth = this.lineWidth;
            this.context.lineCap = 'square';
            this.context.lineJoin="bevel";
        }

        /**
         * 重绘
         */
        redraw() {
            this.context.clearRect(0, 0, this.width, this.height);
            let { width, height} = this.originImageData;
            // 宽高比需每次旋转后需重新计算
            let widthRatio = this.width / width;
            let heightRatio = this.height / height;
            this.context.scale(widthRatio, heightRatio);
            this.context.translate(width/2, height/2)
            this.context.rotate(this.rotateAngle * 90 * Math.PI / 180 )
            this.context.drawImage(this.originImageData, -width/2, -height/2)
            // 重置鼠标坐标
            this.context.setTransform(1, 0, 0, 1, 0, 0);
        }

        windowToCanvas(canvas:Element, x:Number, y:Number) {
            var bbox = canvas.getBoundingClientRect();

            return {
                x: (x - bbox.left) * (canvas.width / bbox.width),
                y: (y - bbox.top) * (canvas.height / bbox.height)
            }
        }

        /**
         * 加载图片
         */
        loadImage() {
            let self = this;
            const loading = this.$loading({
            });
            let imageObj = new Image()
            imageObj.crossOrigin = "anonymous";
            imageObj.onload = function() {
                self.originImageData = imageObj;
                self.redraw()
                loading.close()
            }
            imageObj.src = this.image
        }

        /**
         * 移除 URL 参数
         */
        removeUrlParam(url) {
            return url.replace(/\?.+$/, '');
        }

        // closeDialog () {
        //     this.cleanBoard();
        //     this.$emit('closeDialog','')
        // }

        mounted() {
            this.context = this.$refs.drawingboard.getContext('2d');
            this.loadImage();
            this.switchCxt();
        }
    }
</script>

<style lang="scss" scoped>
    .image_paint {
        // display: inline-block;
        // position: relative;
        // box-sizing: border-box;
        // cursor: zoom-in;
        .paint {
            // width: 100%;
            // height: 100%;
            border: 1px solid goldenrod;
        }
    }

    .lineWidth {
        background-color: #C8C8C8;
        vertical-align: middle;
        width: 100%;
        display: inline-block;
    }
</style>